package org.niux.AutoLoginQQ.operate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.eclipse.swt.widgets.Display;
import org.niux.AutoLoginQQ.VO.QQNumVO;
import org.niux.AutoLoginQQ.common.Constant;
import org.niux.AutoLoginQQ.ui.Main;

/**
 * 所有任务接口 其他任务必须继承访类
 * 
 * @author obullxl
 */
public class LoginTask implements Runnable {
	private Log log = LogFactory.getLog(this.getClass());

	/* 产生时间 */
	private Date generateTime = null;
	/* 提交执行时间 */
	private Date submitTime = null;
	/* 开始执行时间 */
	private Date beginExceuteTime = null;
	/* 执行完成时间 */
	private Date finishTime = null;

	private long taskId;

	private Main gui;

	private QQNumVO qqNumVO;

	private boolean canNoVerify;

	public LoginTask(QQNumVO qqNumVO, Main gui, boolean canNoVerify) {
		this.generateTime = new Date();
		this.qqNumVO = qqNumVO;
		this.gui = gui;
		this.canNoVerify = canNoVerify;
	}

	/**
	 * 任务执行入口
	 */
	public void run() {
		// // 获取用户名
		// String userName = getUserName(responseString);

		// // 更新界面表格的用户名字段
		// updateUserName(qqNumVO.getIndex(), userName);

		this.beginExceuteTime = new Date();

		// 第二次登录
		LoginQQ login = new LoginQQ(gui);

		login.updateWaitingLogin(Integer.toString(Constant.LOGIN_QUEEN.size()));

		String responseString = login.secondLogin(qqNumVO.getHttpClient(),
				qqNumVO, canNoVerify);
		log.debug(qqNumVO.getQqNum()+"第二次登录返回数据："+responseString);

		if (responseString == null || "null".equals(responseString)) {
			// 登录失败的处理
			login.updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "第二次登录连接超时，请稍后重新登录");
			Constant.LOGIN_COUNT--; // 已登录个减1
			return;
		} else if(responseString.equals("cookies")){
			//添加到等待队列中
			login.updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "cookies过期，等待重新登录");
			Constant.LOGIN_COUNT--; // 已登录个减1
			Constant.LOGIN_QUEEN.add(qqNumVO);
			login.updateWaitingLogin(Integer.toString(Constant.LOGIN_QUEEN.size()));
			return;
		}

		// 保存登录数据
		// 获取cookies
		List<Cookie> cookies = ((AbstractHttpClient) qqNumVO.getHttpClient())
				.getCookieStore().getCookies();
		log.debug("获取成功登录的Cookies");

		log.debug("保存Cookies");
		List<Cookie> saveCookies = new ArrayList<Cookie>();
		if (!Constant.LOGIN_DATA.containsKey(qqNumVO.getQqNum())) {
//			for (Cookie cookie : cookies) {
//				if (cookie.getName().equals("confirmuin")) {
//					BasicClientCookie confirmuin = new BasicClientCookie(
//							"confirmuin", "0");
//					confirmuin.setDomain("qq.com");
//					confirmuin.setPath("/");
//
//					saveCookies.add(confirmuin);
//				} else if (cookie.getName().equals("verifysession")) {
//					saveCookies.add(cookie);
//				} else if (cookie.getName().equals("pt2gguin")) {
//					saveCookies.add(cookie);
//				} else if (cookie.getName().equals("uin")) {
//					saveCookies.add(cookie);
//				} else if (cookie.getName().equals("skey")) {
//					saveCookies.add(cookie);
//				} else if (cookie.getName().equals("ptisp")) {
//					saveCookies.add(cookie);
//				} else if (cookie.getName().equals("RK")) {
//					saveCookies.add(cookie);
//				} else if (cookie.getName().equals("ptuserinfo")) {
//					saveCookies.add(cookie);
//				} else if (cookie.getName().equals("ptcz")) {
//					saveCookies.add(cookie);
//				} else if (cookie.getName().equals("ptwebqq")) {
//					saveCookies.add(cookie);
//				}
//			}
//
//			BasicClientCookie airkey = new BasicClientCookie("airkey", "");
//			airkey.setDomain("qq.com");
//			airkey.setPath("/");
//			saveCookies.add(airkey);

			Constant.LOGIN_DATA.put(qqNumVO.getQqNum(), cookies);
		}

		JSONObject responseJson = JSONObject.fromObject(responseString); // 由JSON转成JSONOBJECT对象
		
		log.debug(responseString);

		JSONObject resultForJson = JSONObject.fromObject(responseJson
				.get("result")); // 获取result部份

		String status = resultForJson.getString("status");
		String vfwebqq = resultForJson.getString("vfwebqq");
		String psessionid = resultForJson.getString("psessionid");

		QQNumVO tempqq = Constant.QQ_LIST.get(qqNumVO.getQqNum());

		if (null == tempqq) {
			// 该QQ已删除
			this.finishTime = new Date();
		}

		// 更新QQ在线状态
		if (status.equals("online")) {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					gui.updateStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "在线"); // 更新界面表格
				}
			});
		} else if (status.equals("callme")) {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					gui.updateStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "Q我吧"); // 更新界面表格
				}
			});
		} else if (status.equals("away")) {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					gui.updateStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "离开"); // 更新界面表格
				}
			});
		} else if (status.equals("busy")) {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					gui.updateStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "忙碌"); // 更新界面表格
				}
			});
		} else if (status.equals("silent")) {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					gui.updateStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "请勿打扰"); // 更新界面表格
				}
			});
		} else if (status.equals("hidden")) {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					gui.updateStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "隐身"); // 更新界面表格
				}
			});
		} else if (status.equals("offline")) {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					gui.updateStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "离线"); // 更新界面表格
				}
			});
		}

		Constant.QQ_LIST.get(qqNumVO.getQqNum()).setPsessionid(psessionid);
		Constant.QQ_LIST.get(qqNumVO.getQqNum()).setHttpClient(qqNumVO.getHttpClient());
		Constant.QQ_LIST.get(qqNumVO.getQqNum()).setLogin(true);
		Constant.QQ_LIST.get(qqNumVO.getQqNum()).setLoginTime(System.currentTimeMillis());
		
		// 添加到已登录队列中
		Constant.ALREADY_LOGIN_QUEEN.add(Constant.QQ_LIST.get(qqNumVO.getQqNum()));
		login.updateAlreadyLogin(Integer.toString(Constant.ALREADY_LOGIN_QUEEN
				.size()));

		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "挂机中..."); // 更新界面表格
			}
		});

		// 获取QQ用户信息
		responseString = login.getUserInfo(qqNumVO.getHttpClient(), qqNumVO,
				vfwebqq);

		while(responseString == null || "null".equals(responseString)){
			log.debug(qqNumVO.getQqNum()+"获取昵称时网络连接失败");
			
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					gui.updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "获取昵称时网络连接失败,正在重新获取..."); // 更新界面表格
				}
			});
			
			responseString = login.getUserInfo(qqNumVO.getHttpClient(), qqNumVO,
					vfwebqq);
		}
//		if (responseString == null || "null".equals(responseString)) {
//			// 连接失败处理
//			this.finishTime = new Date();
//			Display.getDefault().asyncExec(new Runnable() {
//				public void run() {
//					gui.updateOptStatus(qqNumVO.getIndex(), "获取昵称时网络连接失败"); // 更新界面表格
//				}
//			});
//			log.debug(qqNumVO.getQqNum()+"获取昵称时网络连接失败");
//			login.updateOptStatus(qqNumVO.getIndex(), "获取昵称时网络连接失败");// 更新界面表格
//			return;
//		}
		
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "挂机中..."); // 更新界面表格
			}
		});
		
		log.debug("用户信息为：" + responseString);
		Constant.QQ_LIST.get(qqNumVO.getQqNum()).setVfwebqq(vfwebqq);
		Constant.QQ_LIST.get(qqNumVO.getQqNum()).setUserinfoJson(responseString);

		// responseString返回内容是：
		// {"retcode":0,"result":{"face":192,"birthday":{"month":8,"year":1984,"day":28},
		// "occupation":"工程师","phone":"0","allow":0,"college":"辽宁石油化工大学-",
		// "uin":36526630,"constel":8,"blood":0,"homepage":"-","stat":20,
		// "vip_info":0,"country":"","city":"","personal":"","nick":"rUhUa1",
		// "shengxiao":1,"email":"36526630@qq.com","province":"","gender":"female","mobile":"-"}}

		responseJson = JSONObject.fromObject(responseString); // 由JSON转成JSONOBJECT对象
		resultForJson = JSONObject.fromObject(responseJson.get("result")); // 获取result部份

		final String nick = resultForJson.getString("nick").replace(" ", "");
		
		Constant.QQ_LIST.get(qqNumVO.getQqNum()).setNick(nick);

		// 更新界面表格的用户名字段
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.updateUserName(qqNumVO.getIndex(),qqNumVO.getQqNum(), nick);
			}
		});

		// 获取等级信息
		responseString = login.getLevel(qqNumVO.getHttpClient(), qqNumVO,
				vfwebqq);

		while(responseString == null || "null".equals(responseString)){
			log.debug(qqNumVO.getQqNum() + "获取等级信息时网络连接失败");
			
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					gui.updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "获取等级信息时网络连接失败,正在重新获取..."); // 更新界面表格
				}
			});
			
			responseString = login.getLevel(qqNumVO.getHttpClient(), qqNumVO,
					vfwebqq);
		}
		
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "挂机中..."); // 更新界面表格
			}
		});
		
//		if (responseString == null || "null".equals(responseString)) {
//			// 连接失败处理
//			this.finishTime = new Date();
//			Display.getDefault().asyncExec(new Runnable() {
//				public void run() {
//					gui.updateOptStatus(qqNumVO.getIndex(), "获取等级信息时网络连接失败"); // 更新界面表格
//				}
//			});
//			return;
//		}

		responseJson = JSONObject.fromObject(responseString); // 由JSON转成JSONOBJECT对象
		resultForJson = JSONObject.fromObject(responseJson.get("result")); // 获取result部份

		String level = resultForJson.getString("level");
		String days = resultForJson.getString("days");
		String remainDays = resultForJson.getString("remainDays");
		
		Constant.QQ_LIST.get(qqNumVO.getQqNum()).setLevel(level);
		Constant.QQ_LIST.get(qqNumVO.getQqNum()).setOnlineDate(days);
		Constant.QQ_LIST.get(qqNumVO.getQqNum()).setRemainDate(remainDays);

		// 更新等级信息
		login.updateLevelInfo(qqNumVO.getIndex(), qqNumVO.getQqNum(), level, days, remainDays);

		// 如果到达等级上限则退出登录
		if (Integer.parseInt(level) >= Integer.parseInt(Constant.TOP_LEVEL)) {
			log.debug(qqNumVO.getQqNum() + "已到达等级上限");
			login.addLogoutQueen(qqNumVO.getQqNum(), "已到达等级上限");

			Constant.QQ_LIST.get(qqNumVO.getQqNum()).setHttpClient(
					qqNumVO.getHttpClient());

			login.updateWaitingLogin(Integer.toString(Constant.LOGIN_QUEEN
					.size()));
		}

		// 获取个性签名
		// 返回内容是：{"retcode":0,"result":[{"uin":36526630,"lnick":"我知道，时间不曾为谁停留过"}]}
		responseString = login.getSingleLongNick(qqNumVO.getHttpClient(),
				qqNumVO, vfwebqq);

		while(responseString == null || "null".equals(responseString)){
			log.debug(qqNumVO.getQqNum() + "获取个性签名时网络连接失败");
			
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					gui.updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "获取个性签名时网络连接失败,正在重新获取..."); // 更新界面表格
				}
			});
			
			responseString = login.getSingleLongNick(qqNumVO.getHttpClient(),
					qqNumVO, vfwebqq);
		}
		
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				gui.updateOptStatus(qqNumVO.getIndex(),qqNumVO.getQqNum(), "挂机中..."); // 更新界面表格
			}
		});
		
		log.debug(responseString);
		responseJson = JSONObject.fromObject(responseString); // 由JSON转成JSONOBJECT对象
		JSONArray lnickArray = JSONArray.fromObject(responseJson.get("result")); // 获取result部份

		String singleLongNick = "";

		for (Object object : lnickArray) {
			JSONObject lnickObj = JSONObject.fromObject(object);
			singleLongNick = lnickObj.getString("lnick").replace(" ", "");
		}

		log.debug("个性签名是：" + singleLongNick);

		Constant.QQ_LIST.get(qqNumVO.getQqNum()).setNick(nick);
		Constant.QQ_LIST.get(qqNumVO.getQqNum()).setSingleLongNick(singleLongNick);

		this.finishTime = new Date();
	}

	public Date getGenerateTime() {
		return generateTime;
	}

	public Date getBeginExceuteTime() {
		return beginExceuteTime;
	}

	public void setBeginExceuteTime(Date beginExceuteTime) {
		this.beginExceuteTime = beginExceuteTime;
	}

	public Date getFinishTime() {
		return finishTime;
	}

	public void setFinishTime(Date finishTime) {
		this.finishTime = finishTime;
	}

	public Date getSubmitTime() {
		return submitTime;
	}

	public void setSubmitTime(Date submitTime) {
		this.submitTime = submitTime;
	}

	public long getTaskId() {
		return taskId;
	}

	public void setTaskId(long taskId) {
		this.taskId = taskId;
	}

}
